﻿using Pb;
using ServerCommon.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ServerCommon.Net
{
    public class ProtocolList
    {
        private static readonly LogHelper Log = LogHelper.GetLogger(typeof(ProtocolList));

        private static readonly Dictionary<int, ProtocolParser> ProtocolIdParserMap = new Dictionary<int, ProtocolParser>();

        // ToDo 后续靠protobuf功能，反射寻找id
        public static void Register()
        {
            RegisterProtocol((int)Pb.EnumProtocolId.ServerInitReq, ProtocolParser.Create<S2SServerInitReq>());
            RegisterProtocol((int)Pb.EnumProtocolId.ServerInitAck, ProtocolParser.Create<S2SServerInitAck>());
        }

        private static void RegisterProtocol(int protocolId, ProtocolParser protocolParser)
        {
            if (ProtocolIdParserMap.ContainsKey(protocolId))
            {
                Log.Error($"节点服务类型中协议重复注册, protocolId={protocolId}");
                return;
            }
            protocolParser.SetProtocolId(protocolId);
            ProtocolIdParserMap.Add(protocolId, protocolParser);
        }

        public static ProtocolParser GetParser(EnumNodeServiceType serviceType, int protocolId)
        {
            return GetParser(protocolId);
        }

        public static ProtocolParser GetParser(int protocolId)
        {
            ProtocolIdParserMap.TryGetValue(protocolId, out var parse);
            return parse;
        }

        public static int ParseId(byte[] data, int offset = 0)
        {
            return System.BitConverter.ToInt32(data, offset);
        }
    }
}
